package service

import (
	"fmt"
	"image-server/config"
	models "image-server/dao"
	"image-server/dao/model"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
)

// ShareService 分享服务
type ShareService struct{}

// GetUserShares 获取用户的所有分享记录
func (s *ShareService) GetUserShares(userID int64, page, limit int) ([]model.Share, int64, error) {
	// 直接调用模型层方法查询该用户的分享记录
	shares, total, err := models.GetSharesByUserID(userID, page, limit)
	if err != nil {
		return nil, 0, fmt.Errorf("获取分享记录失败: %w", err)
	}
	return shares, total, nil
}

// STSCredential STS临时凭证结构
type STSCredential struct {
	AccessKeyID     string `json:"access_key_id"`
	AccessKeySecret string `json:"access_key_secret"`
	SecurityToken   string `json:"security_token"`
	Expiration      string `json:"expiration"` // 过期时间(UTC格式)
	Region          string `json:"region"`
	Bucket          string `json:"bucket"`
}

// GetUploadCredentials 获取上传用的STS凭证
// 权限限制：仅允许向用户目录上传文件
func (s *ShareService) GetUploadCredentials(userId int64, wpsSID string, expiration int) (*STSCredential, error) {
	return s.getSTSCredentials(
		userId,
		"oss:PutObject", // 仅允许上传操作
		fmt.Sprintf("acs:oss:*:*:%s/%d_%s/*", config.Aliyun.Bucket, userId, wpsSID),
		expiration,
	)
}

// 通用获取STS凭证方法
func (s *ShareService) getSTSCredentials(userId int64, action, resource string, expiration int) (*STSCredential, error) {
	// 创建STS客户端
	client, err := config.NewSTSClient()
	if err != nil {
		return nil, fmt.Errorf("创建STS客户端失败: %w", err)
	}

	// 构造请求
	request := sts.CreateAssumeRoleRequest()
	request.Scheme = "https"
	request.RoleArn = config.Aliyun.STSRoleARN                // RAM角色ARN
	request.RoleSessionName = fmt.Sprintf("user-%d", userId)  // 角色会话名称
	request.DurationSeconds = requests.NewInteger(expiration) // 有效期(秒)

	// 权限策略：限制操作和资源
	request.Policy = fmt.Sprintf(`{
		"Version": "1",
		"Statement": [{
			"Effect": "Allow",
			"Action": ["%s"],
			"Resource": ["%s"]
		}]
	}`, action, resource)

	// 发起请求
	response, err := client.AssumeRole(request)
	if err != nil {
		return nil, fmt.Errorf("获取STS凭证失败: %w", err)
	}

	return &STSCredential{
		AccessKeyID:     response.Credentials.AccessKeyId,
		AccessKeySecret: response.Credentials.AccessKeySecret,
		SecurityToken:   response.Credentials.SecurityToken,
		Expiration:      response.Credentials.Expiration,
		Region:          config.Aliyun.Region,
		Bucket:          config.Aliyun.Bucket,
	}, nil
}
